<template>
	<view class="main" >
		<view v-if="show" class="title-bar">
			<!-- 聊天模式标题 -->
			<pop-menu :showMenu.sync="isMore" :menu-list="currentMenu" @menu-click="menuClick" menuBgColor="#55aaff" item-color="#ffffff" :menuZIndex="9999"></pop-menu>
			<view v-if="queryParam.type === 'chat'&&!searchShow" class="title-content">
				<view class="title-btn left-btn" @click="popleft">
					<uni-icons type="bars" size="20" color="#fff"></uni-icons>
				</view>
				<view class="title-middle">
					<text class="title-text u-line-1">{{ isws ? address.addressShort : '连接中...' }}</text>
				</view>
				<view class="title-btn right-btn" @click="toSearch">
					<uni-icons type="search" size="20" color="#fff"></uni-icons>
				</view>
			</view>
			<!--  公共聊天区 -->
			<view v-else-if="queryParam.type === 'public'&&!searchShow" class="title-content">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="nicpic-box">
					<uni-icons type="location" size="30" color="#fff"></uni-icons>
				</view>

				<view class="title-middle">
					<text class="title-text u-line-2">{{ address.addressShort }}</text>
				</view>
				<view class="title-btn right-btn" @click="handMore">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 个人聊天标题 -->
			<view class="title-content" v-else-if="queryParam.type === 'person'&&!searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="title-middle person-info">
					<view class="avatar-container">
						<view class="nicpic-box" v-if="toTarget.nicPic">
							<image class="nicpic" :src="toTarget.nicPic" mode="aspectFill"></image>
						</view>
						<view v-else class="fallback-avatar">
							<avatar-fallback :name="toTarget.targetName || '未知'" :size="40" text-color="#fff"></avatar-fallback>
						</view>
					</view>
					<view class="name-container">
						<text class="title-text">{{ toTarget.targetName || '未知用户' }}</text>
						<!-- 可添加在线状态等信息 -->
						<text class="status-text" v-if="toTarget.online">在线</text>
					</view>
				</view>
				<view class="title-btn right-btn" @click="handMore">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 收藏标题 -->
			<view class="title-content" v-else-if="queryParam.type === 'favorite'&&!searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="nicpic-box">
					<uni-icons type="star-filled" size="30" color="#ffaa00"></uni-icons>
				</view>

				<view class="title-middle person-info">
					<text class="title-text">{{ toTarget.targetName }}</text>
				</view>
				<view class="title-btn right-btn" @click="handMore">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 群聊标题 -->
			<view class="title-content" v-else-if="queryParam.type === 'group'&&!searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="title-middle">
					<text class="title-text">{{ toTarget.targetName || '群聊' }}</text>
					<text class="subtitle-text" v-if="toTarget.memberCount">{{ toTarget.memberCount }}人</text>
				</view>
				<view class="title-btn right-btn" @click="handMore">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 陌生人标题 -->
			<view class="title-content" v-else-if="queryParam.type === 'stranger'&&!searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="avatar-container">
					<view class="fallback-avatar">
						<avatar-fallback :name="toTarget.targetName || '未知'" :size="40" text-color="#fff"></avatar-fallback>
					</view>
				</view>
				<view class="title-middle person-info">
					<text class="title-text">{{ toTarget.targetName }}</text>
				</view>
				<view class="title-btn right-btn" @click="handMore">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>

			<!-- 管理员标题 -->
			<view class="title-content" v-else-if="queryParam.type === 'own'&&!searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="title-middle">
					<text class="title-text">管理员</text>
				</view>
				<view class="title-btn right-btn">
					<uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
				</view>
			</view>
			<view class="title-content" v-else-if="searchShow">
				<view class="title-btn left-btn" @click="naviback">
					<uni-icons type="left" size="20" color="#fff"></uni-icons>
				</view>
				<view class="search-bar" >
					<input class="search" type="text"  @input="onSearch"  :placeholder="placeholder" confirm-type="search" placeholder-style="color:#ffffff;fontSize:26rpx" />
				</view>             
			</view>
			
			
		</view>
		<uni-popup ref="popup" type="center">
			<view class="" v-for="(pic, index) in pics" :key="index">
				<view class="picbox" @click="changPic(pic)">
					<image class="pic" :src="pic.url" mode="aspectFill"></image>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import AvatarFallback from '@/components/AvatarFallback.vue';
const friend = uniCloud.importObject('friend',{customUI:true});
import popMenu from './popMenu.vue';

export default {
	name: 'chatTitle',

	components: {
		AvatarFallback,
		popMenu
	},
	computed: {
		address() {
			const res=this.$store.state.msg.address 
				
			if(typeof(res)!=='object'||Object.keys(res).length===0){
				return '连接中...'
			}
			return res
		},
		isws() {
			return this.$store.state.msg.ws && this.$store.state.msg.ws.readyState === 1;
		},
		queryParam() {
			return this.$store.state.msg.queryParam;
		},
		toTarget() {
			return this.$store.state.msg.toTarget;
		},
		currentMenu() {
			// 根据当前类型返回对应菜单
			const { type } = this.queryParam;
			switch (type) {
				case 'public':
					return this.publicMenu;
				case 'person':
				case 'stranger':
					return this.personMenu;
				case 'favorite':
					return this.favoriteMenu;
				case 'group':
					return this.groupMenu;
				default:
					return [];
			}
		}
	},
	props: {
		show: {
			type: Boolean,
			default: true
		},
		placeholder:{
			type:String,
			default:'输入搜索内容'
		},
		searchShow:{
			type:Boolean,
			default:false
		}
	},
	data() {
		return {
			isMore: false,
			pics: [ {type:'no-repeat',url:'/static/background/bk2.png'}, {type:'no-repeat',url:'/static/background/bk1.png'}, {type:'no-repeat',url:'/static/background/bk3.png'} ],
			publicMenu: [
				{ label: '地图查找', value: 'toMap' },
				{ label: '邀请好友', value: 'addFriend' },
				{ label: '回到本地', value: 'toLocation' },
				{ label: '更换背景', value: 'changeBackGround' }
			],
			favoriteMenu: [
				{ label: '地图查找', value: 'toMap' },
				{ label: '邀请好友', value: 'addFriend' },
				{ label: '回到本地', value: 'toLocation' }
			],
			personMenu: [
				{ label: '好友详情', value: 'friendDetail' },
				// { label: '创建群聊', value: 'madeGroup' },
				{ label: '删除记录', value: 'delPersonMsgRecord' },
				{ label: '拉黑删除', value: 'blockFriend' }
			]
		
		};
	},
	methods: {
		popleft() {
			this.$emit('popleft');
		},
		naviback() {
			uni.navigateBack();
		},
		toSearch() {
			uni.navigateTo({
				url:'/pages/searchPage/searchPage',
				animationType:'fade-in'
			});
		},
	
		handMore() {
			if(this.queryParam.type==='group'){
				uni.navigateTo({
				url:`/pages/groupDetail/groupDetail?id=${this.toTarget.targetId}`
				})
				return
			}
			this.isMore = true;
		},
		menuClick(e) {
			switch (e.item.value) {
				case 'friendDetail':
					this.friendDetail();
					break;
				case 'delPersonMsgRecord':
					this.delPersonMsgRecord();
					break;
				case 'blockFriend':
					this.blockFriend();
					break;
				case 'toMap':
					this.toMap();
					break;
				case 'toLocation':
					this.toLocation();
					break;
				case 'addFriend':
					this.addFriend();
					break;
				case 'changeBackGround':
					this.changeBackground();
					break;
				
					
				default: {
				}
			}
		},
	
		toLocation() {
			this.$store.commit('msg/SET_isFly', false);
			this.$store.commit('msg/SET_location', this.$store.state.msg.senderLocation);
			uni.navigateBack();
		},
		friendDetail() {
			uni.navigateTo({
				url: `/pages/friend/friend?id=${this.toTarget.targetId}`
			});
		},
		delPersonMsgRecord() {
			if (!this.toTarget?.targetId) {
				uni.showToast({ title: '无法获取聊天对象', icon: 'none' });
				return;
			}
			const MSG_PERSON_PREFIX = 'msg_person_';
			const storageKey = `${MSG_PERSON_PREFIX}${this.toTarget.targetId}`;

			uni.showModal({
				title: '删除聊天记录',
				content: '删除记录后无法恢复，确认？',
				success: (res) => {
					if (res.confirm) {
						uni.removeStorageSync(storageKey);
						uni.showToast({ title: '记录已删除', icon: 'success' });
						// 清空当前页面的聊天记录列表（根据实际数据结构调整）
						this.$store.commit('msg/SET_publicMessageList', []);
						this.$emit('Refresh');
						console.log('删除后的内存', uni.getStorageSync(storageKey));
						console.log('删除后的VUE', this.$store.state.msg.publicMessageList);
					}
				}
			});
		},
		changeBackground() {
			this.$refs.popup.open();
		},
		changPic(pic) {
			uni.setStorageSync('backPic', pic);
			this.$refs.popup.close();
			this.$emit('backgroudPic', pic);
		},
		addFriend() {
			uni.navigateTo({
				url: '/pages/contactPage/contactPage'
			});
		},
		async blockFriend() {
			try {
				const param = {
					userId:"",
					friendUserId:"",
					isBlock:true
				}
		
				param.userId = this.$store.state.msg.user?.userId;
				param.friendUserId = this.toTarget.targetId;
			 
				const res = await friend.blockFriend(param);
				if (res.success) {
					uni.showToast({
						title: res.message,
						position: 'center'
					});
				} else {
					uni.showToast({
						title: '拉黑失败稍后再试',
						icon: 'fail'
					});
				}
			} catch (e) {
				console.error(e);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
// 基础样式变量
$title-height: 130rpx;
$btn-size: 60rpx;
$padding-horizontal: 30rpx;
$primary-color: #438acc;
$light-primary: #5a9cd8;
$text-color: #fff;
$subtitle-color: rgba(255, 255, 255, 0.8);

.title-bar {
	height: $title-height;
	position: fixed;
	transform-style: preserve-3d;
	transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s;
	top: 0;
	padding-top: 50rpx;
	padding: 0 $padding-horizontal;
	padding-top: 50rpx;
	left: 0;
	right: 0;
	z-index: 100;
	background-color: $primary-color;
	display: flex;
	align-items: center;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); // 增加轻微阴影提升层次感

	.title-content {
		display: flex;
		align-items: center;
		width: 100%;
		height: 100%;
	}

	// 左右按钮样式
	.title-btn {
		width: $btn-size;
		height: $btn-size;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: background-color 0.2s;

		&:active {
			background-color: $light-primary; // 点击反馈
		}
	}

	.left-btn {
		margin-right: 10rpx;
	}

	.right-btn {
		position: relative;
		margin-left: auto; // 右对齐
	}

	// 中间标题区域
	.title-middle {
		flex: 1; // 占满剩余空间
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 0; // 解决文本过长问题
		padding: 0 20rpx;

		.title-text {
			color: $text-color;
			font-size: 30rpx;
			font-weight: 600;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.subtitle-text {
			color: $subtitle-color;
			font-size: 24rpx;
			margin-left: 10rpx;
		}
	}

	// 个人信息特殊样式
	.person-info {
		justify-content: flex-start; // 个人信息左对齐

		.avatar-container {
			margin-right: 20rpx;

			.nicpic-box {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				overflow: hidden;
				border: 2rpx solid rgba(255, 255, 255, 0.2);

				.nicpic {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}

			.fallback-avatar {
				width: 80rpx;
				height: 80rpx;
			}
		}

		.name-container {
			display: flex;
			flex-direction: column;
			justify-content: center;

			.status-text {
				color: $subtitle-color;
				font-size: 24rpx;
				margin-top: 4rpx;
			}
		}
	}
}

// 适配不同设备的顶部安全区域
::v-deep .uni-page-head {
	padding-top: env(safe-area-inset-top);
}
.picbox{
	width: 120rpx;
	height: 120rpx;
	margin: 10rpx;
	border-radius: 16rpx;
	.pic{
    width: 120rpx;
    height: 120rpx;
    border-radius: 16rpx;	
}
}
/* 搜索栏 */
.search-bar {
	display: flex;
	align-items: center;
	padding: 10px 15px;
	// border-bottom: 1px solid #eee;
    .search{
		color: #fff;
	}
	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		height: 32px;
		padding: 0 10px;
		background-color: #f5f5f5;
		border-radius: 16px;

		.search-icon {
			margin-right: 5px;
		}

		input {
			flex: 1;
			height: 100%;
			font-size: 14px;
			color: #333;

			.placeholder {
				color: #999;
			}
		}

		.clear-icon {
			padding: 3px;
			cursor: pointer;
		}
	}

	.cancel-btn {
		width: 50px;
		text-align: center;
		color: #007aff;
		font-size: 14px;
		cursor: pointer;
	}
}

</style>
